<script setup lang="ts">
import { useGetAreaTree,useGetProjectList} from "@fl/api/elevator-api";
import type { cascadeParam } from "@fl/api/add-elevator-api/model/apply-model";
import { useReformInstallationProjectSave } from "@fl/api/elevator-api";
import { SubmitBtn } from "@fl/components";
import { useUserStoreWithOut } from "@fl/store/modules/user";
import { cloneDeep } from "lodash-es";
import type { PlusColumn } from "plus-pro-components";
const userStore = useUserStoreWithOut();
const enterpriseTypeName = userStore.getOrgInfo?.enterpriseTypeName ?? "";
const isArea = computed(
  () =>
    userStore.getOrgInfo?.enterpriseAccount != "4201" &&
    enterpriseTypeName == "市住更局(电梯加装)"
);
const visible = defineModel<boolean>("visible", { required: true });

const formRef = ref();

const initialState = {
  areaCode: isArea.value ? userStore.getOrgInfo?.userName.slice(0, 3) : "",
  areaName: "",
  streetCode: "",
  streetName: "",
  communityId: "",
  communityName: "",
  projectId: "",
  projectName: "",
  num: undefined,
};
const state = ref(cloneDeep(initialState));

const isLoading = ref<boolean>(false);
// 级联选择
const initialParams = {
  targetLabel: isArea.value ? "street" : "area",
  areaCode: isArea.value ? userStore.getOrgInfo?.enterpriseAccount : "",
  streetCode: "",
  communityId: "",
  time: undefined, // 刷新用，每次选择后都调用接口
};
const areaParams = ref<cascadeParam>(cloneDeep(initialParams));
const streetParams = ref<cascadeParam>(cloneDeep(initialParams));
const communityParams = ref<cascadeParam>(cloneDeep(initialParams));
const projectParams = ref<cascadeParam>(cloneDeep(initialParams));

const isProjectFocus = ref<boolean>(false);

areaParams.value.targetLabel = "area";

watch(
  () => visible.value,
  () => {
    if (visible.value) {
      reset();
    }
  }
);

// 下拉框：过滤数据
const areaOptions = ref<any>();
const streetOptions = ref<any>();
const communityOptions = ref<any>();
const projectOptions = ref<any>();

// 下拉框：原数据
const projectOriginOptions = ref<any>([]);

const { data: areaList } = useGetAreaTree(areaParams);
const { data: streetList } = useGetAreaTree(streetParams);
const { data: communityList } = useGetAreaTree(communityParams);
const { data: projectList } = useGetProjectList(projectParams);

watchEffect(() => {
  if (areaList.value) {
    areaOptions.value = cloneDeep(areaList.value);
  }
  if (streetList.value) {
    streetOptions.value = cloneDeep(streetList.value);
  }
  if (communityList.value) {
    communityOptions.value = cloneDeep(communityList.value);
  }
  if (projectList.value) {
    projectOptions.value = cloneDeep(projectList.value);
    projectOriginOptions.value = cloneDeep(projectList.value);
  }
});

const isStreetDisabeld = computed(() => {
  return !state.value.areaCode;
});

const isCommunityDisabeld = computed(() => {
  return isStreetDisabeld.value || !state.value.streetCode;
});
const isProjectDisabeld = computed(() => {
  return isCommunityDisabeld.value || !state.value.communityId;
});
// 清空街道
function clearStreet() {
  state.value.streetCode = "";
  state.value.streetName = "";
  clearCommunity();
}

// 清空社区
function clearCommunity() {
  state.value.communityId = "";
  state.value.communityName = "";
}
// 清空小区
function clearProject() {
  state.value.projectId = "";
  state.value.projectName = "";
  isProjectFocus.value = false;
}
// 1.选择区
function areaChange() {
  //清空
  state.value.streetCode = "";
  state.value.communityId = "";
  clearStreet();

  const target = areaOptions.value.find((v: any) => v.value === state.value.areaCode);
  state.value.areaName = target.label;
  streetParams.value.targetLabel = "street";
  streetParams.value.areaCode = state.value.areaCode;
  streetParams.value.time = new Date().getTime();
  // console.log('streetParams.value', streetParams.value)
}

// 2.街道选择
function streetChange() {
  //清空
  state.value.communityId = "";
  // state.value.projectName = '' // ?
  clearCommunity();

  const target = streetOptions.value.find((v: any) => v.value === state.value.streetCode);
  state.value.streetName = target.label;
  communityParams.value.targetLabel = "community";
  communityParams.value.streetCode = state.value.streetCode;
  communityParams.value.time = new Date().getTime();
  // console.log('communityParams.value', streetParams.value)
}

function communityChange() {
  //清空
  state.value.projectId = "";
  // state.value.projectName = '' // ?
  clearProject();


  const target = communityOptions.value.find(
    (v: any) => v.value === state.value.communityId
  );
  state.value.communityName = target.label;
  projectParams.value.targetLabel = "project";
  projectParams.value.communityId = state.value.communityId;
  projectParams.value.time = new Date().getTime();
  // console.log('projectParams.value', streetParams.value)
}
// 4.小区选择
function projectFocus() {
  isProjectFocus.value = true;
}
function projectBlur() {
  isProjectFocus.value = false;
}
function chooseProject(item) {
  state.value.projectName = item.label;
  state.value.projectId = item.value;
  projectBlur();
}
function projectInput() {
  if (!state.value.projectName) {
    clearProject();
  } else {
    state.value.projectId = "";
  }
  projectOptions.value = projectOriginOptions.value.reduce((pre, cur) => {
    // state.value.projectName &&
    if (cur.label.indexOf(state.value.projectName) > -1) {
      pre.push(cur);
    }
    return pre;
  }, []);
  // 无匹配数据，
}

// 提交表单
const { isPending, mutate } = useReformInstallationProjectSave();

// 提交
async function submit() {
  const valid = await formRef.value.formInstance.validate();
  if (valid) {
    const params = {
      ...unref(state),
      areaCode: state.value.areaCode || null, // 后端要求传null
      streetCode: state.value.streetCode || null,
      communityId: state.value.communityId || null,
      projectId: state.value.projectId || null,
    };
    mutate(params, {
      onSuccess: () => {
        ElMessage.success("操作成功");
        cancel();
      },
    });
  }
}

function cancel() {
  visible.value = false;
  reset();
}

function reset() {
  state.value = cloneDeep(initialState);
  formRef.value?.formInstance.resetFields();
  projectOptions.value = [];
  isProjectFocus.value = false;

}

const columns: PlusColumn[] = [
  {
    label: "所在区",
    prop: "areaCode",
  },
  {
    label: "街道",
    prop: "streetCode",
  },
  {
    label: "社区",
    prop: "communityId",
  },
  {
    label: "小区",
    prop: "projectName",
  },
  {
    label: "小区编码",
    prop: "projectId",
    fieldProps: {
      disabled: enterpriseTypeName != "信息中心(电梯加装)",
    },
  },
];

const rules = computed(() => ({
  areaCode: [
    {
      message: "所在区",
      required: true,
    },
  ],
  streetCode: [
    {
      message: "街道",
      required: true,
    },
  ],
  communityId: [
    {
      message: "社区",
      required: true,
    },
  ],
  projectName: [
    {
      message: "小区",
      required: true,
    },
  ],
  projectId: [
    {
      message: "小区编码",
      //   required: true,
    },
  ],
}));
</script>

<template>
  <el-drawer v-model="visible" :size="600">
    <template #header> 新增 </template>
    <ElSkeleton v-if="isLoading" animated class="mt-20" />

    <template v-else>
      <div class="mt-20 plusform">
        <PlusForm
          ref="formRef"
          v-model="state"
          :columns="columns"
          :label-width="120"
          :rules="rules"
          :has-footer="false"
          :row-props="{ gutter: 20 }"
          style="height: 500px"
        >
          <template #plus-field-areaCode>
            <el-select
              v-model="state.areaCode"
              placeholder="请选择"
              :disabled="isArea"
              filterable
              @change="areaChange"
            >
              <el-option
                v-for="item in areaOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>

          <template #plus-field-streetCode>
            <el-select
              v-model="state.streetCode"
              placeholder="请选择"
              filterable
              @change="streetChange"
              :disabled="isStreetDisabeld"
            >
              <el-option
                v-for="item in streetOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
          <template #plus-field-communityId>
            <el-select
              v-model="state.communityId"
              placeholder="请选择"
              filterable
              @change="communityChange"
              :disabled="isCommunityDisabeld"
            >
              <el-option
                v-for="item in communityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
          <template #plus-field-projectName>
            <el-input
              v-model="state.projectName"
              clearable
              @click.stop="projectFocus"
              @input="projectInput"
              :disabled="isProjectDisabeld"
              placeholder="请选择/输入"
            >
            </el-input>
            <div class="positive" v-if="isProjectFocus">
              <div
                class="item"
                v-for="(item, index) in projectOptions"
                :key="index"
                @click="chooseProject(item)"
              >
                {{ item.label }}
              </div>
            </div>
          </template>
        </PlusForm>
      </div>
    </template>

    <template #footer>
      <div class="flex: auto">
        <SubmitBtn type="primary" :loading="isPending" @click="submit"> 提交 </SubmitBtn>

        <el-button @click="cancel"> 取消 </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style lang="scss" scoped>
.plusform {
  // height: 640px;
  overflow-y: auto;
  overflow-x: hidden;
}

.positive {
  position: absolute;
  width: 100%;
    max-height: 160px;
  background: #fff;
  z-index: 10;
  top: 34px;
  left: 0;
  overflow-y: auto;
  border: 1px solid #eee;
  border-radius: 4px;

  .item {
    padding-left: 10px;
    cursor: pointer;
  }

  .item:hover {
    background: #eee;
  }
}
:deep(.el-drawer__body) {
  height: 100%;
}
:deep(.plusform) {
  height: 500px;
}
</style>
